package com.whu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whu.entity.Supplier;
import com.whu.mapper.ProductMapper;
import com.whu.entity.Product;
import com.whu.mapper.SupplierMapper;
import com.whu.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private SupplierMapper supplierMapper;
    @Override
    public Product getById(Long id) {
        Product product = productMapper.selectById(id);
        product.setSuppliers(supplierMapper.selectByPid(id));
        return product;
    }

    @Override
    public List<Product> getAll() {
        List<Product> products = productMapper.selectList(null);
        for (Product product: products) {
            List<Supplier> suppliers = supplierMapper.selectByPid(product.getId());
            product.setSuppliers(suppliers);
        }
        return products;
    }

    @Override
    public boolean saveWithSuppliers(Product product) {
        int flag1 = productMapper.insert(product);
        int flag2 = 0;
        for(Supplier supplier : product.getSuppliers()){
            supplier.setPid(product.getId());
            flag2 = supplierMapper.insert(supplier);
        }

        return flag1 > 0 && flag2 > 0;
    }

    @Override
    public boolean deleteByIdWithSuppliers(Long id) {
        int flag1 = productMapper.deleteById(id);
        int flag2 = 0;
        for(Supplier supplier : supplierMapper.selectByPid(id)){

            flag2 = supplierMapper.deleteById(supplier);
        }
       return flag1 > 0 && flag2 > 0;
    }

}
